<template>
  <div></div>
</template>
<script>
import { refenceHeaders, getwxpcAppId } from 'api/http/request'
import { LoginApi } from 'api/draft'
export default {
  name: 'Login',
  data() {
    return {
      redirect: '',
      ROOT_URL: this.$GLOBAL.ROOT_URL
    }
  },
  methods: {
    /** 微信授权登录 */
    loginWx() {
      // 非静默授权，第一次有弹框'
      var local = encodeURIComponent(
        window.location.origin + ROOT_URL + 'login' + (this.redirect ? '?redirect=' + this.redirect : '')
      ) // 获取页面url
      var appid = getwxpcAppId()
      var code = this.getUrlCode().code // 截取code
      if (code == null || code === '' || code == undefined) {
        // 如果没有code，则去请求
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&connect_redirect=1&scope=snsapi_userinfo&state=STATE#wechat_redirect`
      } else {
        // GetTokenApi(code)
        //   .then(res => {
        //     // if (!res.errcode) {
        //     // this.login(res.openid)
        //     localStorage.setItem('token', res.msg)
        //     refenceHeaders()
        //     this.$router.push({ path: this.redirect })
        //     // } else {
        //     //   if (res.errcode == 40163) {
        //     //     window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&connect_redirect=1&scope=snsapi_userinfo&state=STATE#wechat_redirect`
        //     //   }
        //     // }
        //   })
        //   .catch(err => {
        //     window.console.log(err)
        //   })
      }
    },
    /** 登录系统 */
    login(openId) {
      LoginApi(openId)
        .then(res => {
          localStorage.setItem('token', res.msg)
          refenceHeaders()
          this.$router.push({ path: this.redirect })
        })
        .catch(err => {
          window.console.log(err)
        })
    },
    /** 获取url中的code */
    getUrlCode() {
      // 截取url中的code方法'
      var url = location.href
      this.winUrl = url
      var theRequest = new Object()
      if (url.indexOf('?') != -1) {
        var str = url.substr(1)
        var strs = str.split('?')
        if (strs.length >= 2) {
          var strs = strs[1].split('&')
          for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
          }
        } else {
          return theRequest
        }
      }
      return theRequest
    }
  },
  // 初始化之前
  beforeCreate() {},
  // 初始化之后
  created() {
    window.console.log(this.$route.query.redirect)

    this.redirect = this.$route.query.redirect
  },
  // 编译挂载之前
  beforeMount() {},
  // 编译挂载之后
  mounted() {
    this.loginWx()
  },
  // 组件更新之前
  beforeUpdate() {},
  // 组件更新之后
  updated() {},
  // 组件销毁之前
  beforeDestroy() {},
  // 组件销毁之后
  destroyed() {},
  components: {}
}
</script>
<style scoped></style>
